Editor = {}
rawset(Editor, "__index", Editor)

function CreateEditor()
	local inst = {}
	setmetatable(inst, Editor)
	return inst
end

function Editor:Run()
	local frame = wx.wxFrame(wx.NULL, wx.wxID_ANY, "OliviaEditor", wx.wxDefaultPosition, wx.wxSize(1024, 768))
	frame:Connect(wx.wxEVT_DESTROY, function() self:OnDestroy() end)
	self.frame = frame

	LoadModule("script/editorview")
	local view = editorview.CreateView(frame, wx.wxRect(0, 0, 400, 400))
	self.view = view

	frame:Show(true)

	local scene = ov.Scene()
	local camera = scene:CreateCamera("MainCam")

	view.render_target:AddViewPort(camera)

	camera.backgroundcolor = 0xff0000ff
	camera.position = ov.Vector3(0, 60, 1000)
	camera.orientation = ov.Quaternion(ov.Vector3(0, 0, -1), 0)

	local entity = scene:CreateEntity("pig.mesh")
	entity.scale = ov.Vector3(5, 5, 5)
	entity:rotate(ov.Quaternion(ov.Vector3(0, 1, 0), -45))

	self.entities = {}
	self.entities[#self.entities + 1] = entity

	self.scene = scene
	self.camera = camera
	self.time = os.clock()

	frame:Connect(wx.wxEVT_IDLE, function(event) self:OnIdle(event) end)
end

function Editor:OnIdle(event)
	local now = os.clock()
	local elapse = now - self.time
	self.view:Update(elapse)
	collectgarbage()
	ov.RenderOneFrame()
	self.time = now
	-- assume we're runing 60 frames per second
	if elapse < 0.012 then wx.wxMilliSleep(10) end
	event:RequestMore()
end

function Editor:OnDestroy()
	print("destroying editor", self.scene)
	for key, v in pairs(self.entities) do
		print("destroy entity", v)
		self.scene:DestroyEntity(v)
	end
	self.scene:DestroyCamera(self.camera)
	self.scene = nil
end